clear all

// This file uses the appended Census block assignments to construct a precinct-county-district crosswalk 

cd "$OutputPath/"
use censusblock_assign_post2000, clear
append using censusblock_assign_pre2010
append using censusblock_assign_post2010

drop _merge
merge m:1 year fstate fcounty ftract fblock using "$OutputPath/census_pop_block"  // m:1 because of blocks split across multiple sldl

drop _merge 		
drop if fstate==11 	// drop  DC

// changes to county codes

// aggregate NY City counties to merge with government finance data (five boroughs use city government instead of county government)
gen nyc=(fstate==36 & (fcounty==5 | fcounty==61 | fcounty==81 | fcounty==85 | fcounty==47))
replace fcounty=61 if nyc==1

// aggregate Kalawao county with Maui (population 80, no government)
replace fcounty=9 if fcounty==5 & fstate==15

// aggregate Bedford Independent City with Bedford County, Virginia (happens in 2014)
replace fcounty=19 if fcounty==515 & fstate==51

// aggregate Clifton Valley with Allegheny County, Virginia
replace fcounty=5 if fcounty==560 & fstate==51

tempfile base
save `base', replace

/// Collapse to county-sldl level

// disaggregate 2010 block population in cases where 2010 blocks are assigned to multiple sldl using land area (pinblock is % of 2010 block area in the sldl-block intersection)

local popcount population urban rural whitenh hispanic white black male female vap cvap
foreach i in `popcount'{
replace `i'=`i'*pinblock_sldl if pinblock_sldl!=.
}

replace sldl=sldu if fstate==31 //treat Nebraska's unicameral legislature as sldl to include in main analysis

replace sldl="" if sldl=="ZZZ" 

drop if sldl=="" ///unknown district assignment (small or zero pop, average population = 35).

//drop if population<10 //creates some small amount of errors with numbers of districts, which creates large error in measure of representation index

// special cases
replace sldl="73" if fcounty==1 & fstate==49 & year==2007 // Beaver County, Utah was only in district 73,  source: https://www.beaver.utah.gov/DocumentCenter/View/792/g2006total?bidId= 

collapse (sum) `popcount' , by(censusyear year fstate fcounty sldl) 


cd "$OutputPath/"
save county_sldl_pop, replace


/// Collapse to county-sldu level

use `base', clear 

// disaggregate 2010 block population in cases where 2010 blocks are assigned to multiple sldu using land area (pinblock is % of 2010 block area in the sldu-block intersection)

foreach i in `popcount'{
replace `i'=`i'*pinblock_sldu if pinblock_sldu!=.
}

replace sldu="" if sldu=="ZZZ" 

drop if sldu=="" ///unknown district assignment

collapse (sum) `popcount' , by(censusyear year fstate fcounty sldu)  

cd "$OutputPath/"
save county_sldu_pop, replace

